﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace Jäckvik_Grupp4
{

    #region Klassbeskrivning Logibokning
    /// <summary>
    /// Klassbeskrivning
    /// </summary>
    #endregion

    public partial class Lodging : Form
    {
       
        private LOGIC.LogicPrivateGuest privateGuest;
        private LOGIC.LogicCompanyGuest companyGuest;
        private LOGIC.LogicLodging currentLodging; 
        private LOGIC.LogicBooking currentBooking; 
        private LOGIC.LogicConference currentConference = new LOGIC.LogicConference();
        private LOGIC.LogicGuest guest = new LOGIC.LogicPrivateGuest();
        private LOGIC.LogicInvoice invoice = new LOGIC.LogicInvoice();
        private LOGIC.LogicErrorhandling errorhand = new LOGIC.LogicErrorhandling();

        private int tempInvoiceID = 0;
        private int tempBookingID = 0;

        public Lodging()
        {
            InitializeComponent();
            privateGuest = new LOGIC.LogicPrivateGuest(LOGIC.LogicSession.TheSession);
            companyGuest = new LOGIC.LogicCompanyGuest(LOGIC.LogicSession.TheSession);
            currentLodging = new LOGIC.LogicLodging(LOGIC.LogicSession.TheSession);
            currentBooking = new LOGIC.LogicBooking();
            Lodging1Info();
            Lodging2Info();
            ConferenceBigInfo();
            ConferenceSmallInfo();
            comboBoxLodgWeekNr.Text = currentLodging.WeekNrFromDate(DateTime.Now.Date).ToString();
            comboBoxCampWeekNr.Text = currentLodging.WeekNrFromDate(DateTime.Now.Date).ToString();
            comboBoxConfWeek.Text = currentLodging.WeekNrFromDate(DateTime.Now.Date).ToString();
            HideThings();           
        }

        decimal logTotPrice;
        decimal sumNoDiscount;


        //************************************************* Hantering av privatgäst ********************************************************//

        private void buttonLäggTillNyPrGäst_Click(object sender, EventArgs e)
        {
            buttonSparaGäst_Log.Visible = true;
            buttonSparaGäst_Log.Enabled = true;

            buttonÅngraVal.Visible = true;            
            textBox_LogPrFName.Enabled = true;
            textBox_LogPrLName.Enabled = true;
            textBox_LogPrAddress.Enabled = true;
            textBox_LogPrZip.Enabled = true;
            textBox_LogPrCity.Enabled = true;
            textBox_LogPrPhone.Enabled = true;
            if (textBox_LogPrCredit.Text == "")
            {
                textBox_LogPrCredit.Text = "10000";
            }
            textBox_LogPrGuestNr.Enabled = false;
        }
        private void buttonÅngraVal_Click(object sender, EventArgs e)
        {
            buttonSparaGäst_Log.Visible = false;
            textBox_LogPrGuestNr.Clear();
            textBox_LogPrFName.Clear();
            textBox_LogPrLName.Clear();
            textBox_LogPrAddress.Clear();
            textBox_LogPrCity.Clear();
            textBox_LogPrZip.Clear();
            textBox_LogPrPhone.Clear();
            textBox_LogPrCredit.Clear();

            textBox_LogPrGuestNr.Enabled = true;
            textBox_LogPrFName.Enabled = true;
            textBox_LogPrLName.Enabled = true;
            textBox_LogPrAddress.Enabled = false;
            textBox_LogPrZip.Enabled = false;
            textBox_LogPrCity.Enabled = false;
            textBox_LogPrPhone.Enabled = false;
            textBox_LogPrCredit.Enabled = false;
        }
       

        private void button_SearchPrGuestL_Click_1(object sender, EventArgs e) //Söker efter befintilig privatgäst i databasen
        {
            if (textBox_LogPrGuestNr.Text != "") // Kontrollerar om det finns ett värde i Gästnr
            {
                if (errorhand.OnlyNumbers(textBox_LogPrGuestNr.Text) == false)
                { MessageBox.Show("Gästnummer får enbart innehålla siffror"); }
                else
                {
                    int tempId = int.Parse(textBox_LogPrGuestNr.Text);
                    dataGridViewPGuest.Enabled = true;
                    dataGridViewPGuest.DataSource = privateGuest.GetGuestById(tempId);
                }
            }

            else if (textBox_LogPrLName.Text != "" && textBox_LogPrFName.Text != "") //Kontrollerar om det finns värden i både förnamn och efternamn.
            {
                string tempLName = textBox_LogPrLName.Text;
                string tempFName = textBox_LogPrFName.Text;
                dataGridViewPGuest.Enabled = true;
                dataGridViewPGuest.DataSource = privateGuest.GetGuestByName(tempLName, tempFName);
            }

            else if (textBox_LogPrFName.Text != "") // Kontrollerar om det finns ett värde i förnamn 
            {
                string tempFName = (textBox_LogPrFName.Text);
                dataGridViewPGuest.Enabled = true;
                dataGridViewPGuest.DataSource = privateGuest.GetGuestByFName(tempFName);
            }

            else if (textBox_LogPrLName.Text != "") // Kontrollerar om det finns ett värde i efternamn
            {
                string tempLName = (textBox_LogPrLName.Text);
                dataGridViewPGuest.Enabled = true;
                dataGridViewPGuest.DataSource = privateGuest.GetGuestByLName(tempLName);
            }

            if (dataGridViewPGuest.RowCount == 0)
                MessageBox.Show("Ingen gäst kunde hittas.");            

        }

        //********************************************** Hantering av en företagsgäst ******************************************************//

        private void tabControl_GuestsL_Click(object sender, EventArgs e) //Visar alternativt döljer momsbelopp för bokningen beroende på typ av gäst.
        {
            if (tabControl_LogGuest.SelectedIndex == 1) //Visar moms de vald gästtyp är företagsgäst
            {
                label_LogNoVat.Visible = true;
                textBox_LogSumNoVat.Visible = true;
                label_LogVat.Visible = true;
                textBox_LogVat.Visible = true;
            }
            else // Döljer momsbelopp de vald gästtyp är privatgäst
            {
                label_LogNoVat.Visible = false;
                textBox_LogSumNoVat.Visible = false;
                label_LogVat.Visible = false;
                textBox_LogVat.Visible = false;
            }
        }

        private void button_LogCoNewGuest_Click(object sender, EventArgs e)
        {
            textBox_LogCoGuestNr.Enabled = false;
            buttonSparaGästCo.Visible = true;
            buttonSparaGästCo.Enabled = true;
            textBox_LogCoOrgNr.Enabled = true;
            textBox_LogCoName.Enabled = true;
            textBox_LogCoReference.Enabled = true;
            textBox_LogCoAddress.Enabled = true;
            textBox_LogCoZip.Enabled = true;
            textBox_LogCoCity.Enabled = true;
            textBox_LogCoPhone.Enabled = true;
            if (textBox_LogCoCredit.Text == "")
            {
                textBox_LogCoCredit.Text = "100000";
            }
        }

        private void buttonÅngraValCo_Click(object sender, EventArgs e)
        {
            buttonSparaGästCo.Visible = false;
            textBox_LogCoGuestNr.Clear();
            textBox_LogCoOrgNr.Clear();
            textBox_LogCoName.Clear();
            textBox_LogCoAddress.Clear();
            textBox_LogCoZip.Clear();
            textBox_LogCoCity.Clear();
            textBox_LogCoReference.Clear();
            textBox_LogCoPhone.Clear();
            textBox_LogCoCredit.Clear();
            textBox_LogCoGuestNr.Enabled = true;
            textBox_LogCoOrgNr.Enabled = true;
            textBox_LogCoName.Enabled = true;


            textBox_LogCoReference.Enabled = false;
            textBox_LogCoAddress.Enabled = false;
            textBox_LogCoZip.Enabled = false;
            textBox_LogCoCity.Enabled = false;
            textBox_LogCoPhone.Enabled = false;
            textBox_LogCoCredit.Enabled = false;
        }       

        private void button_LogSearchCoGuest_Click(object sender, EventArgs e) // Söker efter befintlig företagsgäst i databasen
        {
            if (textBox_LogCoGuestNr.Text != "") //kontrollerar om det finns värde i företagsnamn och söker i så fall på detta.
            {
                if (errorhand.OnlyNumbers(textBox_LogCoGuestNr.Text) == false)
                {
                    MessageBox.Show("Gästnummer får enbart innehålla siffror");
                }
                else
                {
                    int tempID = int.Parse(textBox_LogCoGuestNr.Text);
                    dataGridViewCoGuest.Enabled = true;
                    dataGridViewCoGuest.DataSource = companyGuest.GetCoGuestById(tempID);
                }
            }
            else if (textBox_LogCoOrgNr.Text != "")
            {
                string tempOrgNr = textBox_LogCoOrgNr.Text;
                dataGridViewCoGuest.Enabled = true;
                dataGridViewCoGuest.DataSource = companyGuest.GetCoGuestOrgNr(tempOrgNr);
            }

            else if (textBox_LogCoName.Text != "")
            {
                string tempCoName = textBox_LogCoName.Text;
                dataGridViewCoGuest.Enabled = true;
                dataGridViewCoGuest.DataSource = companyGuest.GetCoGuestName(tempCoName);
            }
            if (dataGridViewCoGuest.RowCount == 0)
            {
                MessageBox.Show("Ingen gäst kunde hittas.");
            }
        }
    
        

        //****************************************************** Spara Bokning ************************************************************//

        private void button_LogSave_Click(object sender, EventArgs e) //Sparar bokning
        {
            try
            {
                if (tabControl_LogGuest.SelectedIndex == 0)//Kontrollerar vilken slags gäst som är vald
                {
                    if (textBox_LogPrGuestNr.Text == "")
                    { MessageBox.Show("Du måste ange en gäst för bokningen \n eller spara gästen innan du kan genomföra bokningen"); }
                    if (errorhand.OnlyLetters(textBox_LogPrFName.Text.Trim()) == false)
                        MessageBox.Show("Förnamn får enbart innehålla bokstäver");
                    else if (errorhand.OnlyLetters(textBox_LogPrLName.Text.Trim()) == false)
                        MessageBox.Show("Efternamn får enbart innehålla bokstäver");
                    else if (textBox_LogPrAddress.Text == "")
                        MessageBox.Show("Du måste ange en gatuadress");
                    else if (errorhand.OnlyNumbers(textBox_LogPrZip.Text.Trim()) == false)
                    { MessageBox.Show("Postnummer får enbart innehålla siffor"); }
                    else if (errorhand.OnlyLetters(textBox_LogPrCity.Text.Trim()) == false)
                        MessageBox.Show("Ort får enbart innehålla bokstäver");
                    else if (errorhand.OnlyNumbers(textBox_LogPrPhone.Text.Trim()) == false)
                        MessageBox.Show("Telefonnummer får enbart innehålla siffor");
                    else
                    {
                        decimal totPrice = decimal.Parse(textBox_LogTotalSum.Text);
                        decimal credit = decimal.Parse(textBox_LogPrCredit.Text);

                        if (credit < totPrice)
                        {
                            DialogResult rusultat = MessageBox.Show("Gästen överskrider kreditgränsen! \nGästens kredit är för låg för den aktuella bokningen", "Viktigt", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {

                            int guestNr = int.Parse(textBox_LogPrGuestNr.Text);
                            int staffID = LOGIC.LogicSession.TheSession.ActiveUser;
                            bool cancelProtection = checkBox_LogCancelProt.Checked;
                            int discount = Convert.ToInt32(textBox_LogDiscount.Text);
                            int price = Convert.ToInt32(textBox_LogTotalSum.Text);
                            int creditLimit = Convert.ToInt32(textBox_LogPrCredit.Text);



                            int newCredit = creditLimit - price;
                            // LOGIC.LogicBooking.CreateBooking(guestNr, staffID, cancelProtection, discount, price);
                            LOGIC.LogicBooking.CreditUpdate(newCredit, guestNr);

                            if (invoice.InvoiceExistCheck(guestNr, DateTime.Today) == true)
                            {
                                int tempBookingID = invoice.GetBookingIDForInvoice(guestNr, DateTime.Today);
                                LOGIC.LogicBooking.BookingRowUpdate(tempBookingID, cancelProtection, price);
                                AddBookingRows(tempBookingID);
                                textBox_LogBookingNr.Text = tempBookingID.ToString();
                            }
                            else
                            {
                                LOGIC.LogicBooking.CreateBooking(guestNr, staffID, cancelProtection, discount, price);
                                AddBookingRows(tempBookingID);
                                if (currentBooking.PeriodBeforeStartDateCheck(guestNr, currentBooking.GetBookingNumber()) == true)
                                {
                                    LOGIC.LogicInvoice.CreateLodgingInvoice(int.Parse(textBox_LogBookingNr.Text), "a");
                                    LOGIC.LogicInvoice.CreateLodgingInvoice(int.Parse(textBox_LogBookingNr.Text), "b");
                                }

                                else
                                {
                                    LOGIC.LogicInvoice.CreateSumInvoice(int.Parse(textBox_LogBookingNr.Text), guestNr, "c", price, "booking", staffID);
                                }
                            }


                            DialogResult rusultat = MessageBox.Show("Bokning är genomförd, din bokninsnummer: " + textBox_LogBookingNr.Text, "Bokningsbekräftelse", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            label_LogConfimation.Text = "Bokningen är genomförd";
                            button_LogSave.Enabled = false;
                            logTotPrice = 0;
                            sumNoDiscount = 0;
                            

                            if (rusultat == DialogResult.OK)
                            {
                                NewBooking();
                            }
                        }
                    }
                }
                else if (tabControl_LogGuest.SelectedIndex == 1)
                {
                    if (textBox_LogCoGuestNr.Text == "")
                    { MessageBox.Show("Du måste ange en gäst för bokningen \n eller spara gästen innan du kan genomföra bokningen"); }
                    else if (textBox_LogCoOrgNr.Text == "")
                        MessageBox.Show("Du måste ange ett organisationsnummer");
                    else if (textBox_LogCoName.Text == "")
                        MessageBox.Show("Du måste ange ett företagsnamn");
                    else if (textBox_LogCoAddress.Text == "")
                        MessageBox.Show("Du måste ange en gatuadress");
                    else if (errorhand.OnlyNumbers(textBox_LogCoZip.Text.Trim()) == false)
                        MessageBox.Show("Postnummer får enbart innehålla siffor");
                    else if (errorhand.OnlyLetters(textBox_LogCoCity.Text.Trim()) == false)
                        MessageBox.Show("Ort får enbart innehålla bokstäver");
                    else if (textBox_LogCoReference.Text == "")
                        MessageBox.Show("Du måste ange en referens");
                    else if (errorhand.OnlyNumbers(textBox_LogCoPhone.Text.Trim()) == false)
                        MessageBox.Show("Telefonnummer får enbart innehålla siffror");
                    else
                    {
                        int guestNr = int.Parse(textBox_LogCoGuestNr.Text);
                        int staffID = LOGIC.LogicSession.TheSession.ActiveUser;
                        bool cancelProtection = checkBox_LogCancelProt.Checked;
                        int discount = Convert.ToInt32(textBox_LogDiscount.Text);
                        int price = Convert.ToInt32(textBox_LogTotalSum.Text);
                        int creditLimit = currentBooking.GetGuestCreditLimit(guestNr);

                        //LOGIC.LogicBooking.CreateBooking(guestNr, staffID, cancelProtection, discount, price);
                        int newCredit = creditLimit - price;
                        LOGIC.LogicBooking.CreditUpdate(newCredit, guestNr);
                        if (invoice.InvoiceExistCheck(guestNr, DateTime.Today) == true)
                        {
                            int tempBookingID = invoice.GetBookingIDForInvoice(guestNr, DateTime.Today);
                            LOGIC.LogicBooking.BookingRowUpdate(tempBookingID, cancelProtection, price);
                            AddBookingRows(tempBookingID);
                            textBox_LogBookingNr.Text = tempBookingID.ToString();
                        }
                        else
                        {
                            LOGIC.LogicBooking.CreateBooking(guestNr, staffID, cancelProtection, discount, price);
                            AddBookingRows(tempBookingID);
                            if (currentBooking.PeriodBeforeStartDateCheck(guestNr, currentBooking.GetBookingNumber()) == true)
                            {
                                LOGIC.LogicInvoice.CreateLodgingInvoice(int.Parse(textBox_LogBookingNr.Text), "a");
                                LOGIC.LogicInvoice.CreateLodgingInvoice(int.Parse(textBox_LogBookingNr.Text), "b");
                            }

                            else
                            {
                                LOGIC.LogicInvoice.CreateSumInvoice(int.Parse(textBox_LogBookingNr.Text), guestNr, "c", price, "booking", staffID);
                            }
                        }

                        DialogResult rusultat = MessageBox.Show("Bokning är genomförd, din bokninsnummer: " + textBox_LogBookingNr.Text, "Bokningsbekräftelse", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        button_LogSave.Enabled = false;
                        label_LogConfimation.Text = "Bokning är genomförd";

                        if (rusultat == DialogResult.OK)
                        {
                            NewBooking();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Något gick fel" + " " + ex);

            }

            logTotPrice = 0;
            sumNoDiscount = 0;
            timerFreeLodging.Enabled = false;
            
        }    

        /// <summary>
        /// Metod som lägger till bokningsrader för bokningen
        /// </summary>
        /// <param name="tempBookingID"></param>
        private void AddBookingRows(int tempBookingID)
        {
            int bookingID;
            if (tempBookingID == default(int))
            {
                 bookingID = currentBooking.GetBookingNumber();
                 
            }
            else
            {
                bookingID = tempBookingID;
            }
            string rentDetails;
            string[] rentDetailsSplit;
            string lodgingId;
            DateTime startDate;
            DateTime stopDate;
            int price;
            int weekNr;

            for (int i = 0; i < listBox_LogReserved.Items.Count; i++)
            {

                rentDetails = listBox_LogReserved.Items[i].ToString();
                rentDetailsSplit = rentDetails.Split('\t', '\t', '\t', '\t', '\t', '\t');

                lodgingId = rentDetailsSplit[0];
                weekNr = int.Parse(rentDetailsSplit[3]);
                startDate = Convert.ToDateTime(rentDetailsSplit[4]);
                stopDate = Convert.ToDateTime(rentDetailsSplit[5]);
                price = int.Parse(rentDetailsSplit[2]);


                LOGIC.LogicBooking.PutInBookingRow(lodgingId,bookingID, startDate, stopDate, price, weekNr);
                //LOGIC.LogicBooking.DropReservedLodging(lodgingId, startDate, stopDate);


                textBox_LogBookingNr.Text = bookingID.ToString();


                label_LogConfimation.Visible = true;
                
                button_LogSave.Enabled = false;

            }

 
        }
        //****************************************************************** Skriva till fil ********************************************************************************//
        private void WriteToFile()
        {
            string cancelFee;
            if (checkBox_LogCancelProt.Checked)
                cancelFee = "JA";
            else
                cancelFee = "NEJ";

            currentBooking.WriteToFile(textBox_LogBookingNr.Text, cancelFee, textBox_LogSumNoVat.Text, textBox_LogVat.Text, textBox_LogTotalSum.Text);
        }
        //=====================================================================================================================

        // Vad gör denna????????
        private void skickaEkonomifilToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentBooking.SendFile();
        }

        //**************************************************************************** Ny bokning **********************************************************************************//
        
        private void button_LogNew_Click(object sender, EventArgs e)
        {
            NewBooking();
        }

        /// <summary>
        /// Metod som tömmar alla fält och listor när bokning har skapats eller man trycker på knappen nytt
        /// </summary>
        private void NewBooking()
        {
            bindingSource1.Clear();
            bindingSourceFreeLodging.Clear();

            dataGridViewPGuest.DataSource = "";
            dataGridViewCoGuest.DataSource = "";

            textBox_LogPrGuestNr.Clear();
            textBox_LogPrGuestNr.Enabled = true;
            textBox_LogPrLName.Clear();
            textBox_LogPrLName.Enabled = true;
            textBox_LogPrFName.Clear();
            textBox_LogPrFName.Enabled = true;
            textBox_LogPrAddress.Clear();
            textBox_LogPrZip.Clear();
            textBox_LogPrPhone.Clear();
            textBox_LogPrCity.Clear();
            textBox_LogPrCredit.Clear();

            if (listBox_LogReserved.Items.Count == 0)
            {
                //listBox_LogReserved.Items.Clear();
            }
            else
            {
                DropReserveTable();
                //listBox_LogReserved.DataSource = null;
                listBox_LogReserved.Items.Clear();
            }
            dataGridView_LogFree.Rows.Clear();

            textBox_LogCancelProt.Text = "0";
            textBox_LogTotalSum.Text = "0";
            textBox_LogDiscount.Text = "0";
            textBox_LogSumNoVat.Text = "0";
            textBox_LogVat.Text = "0";
            logTotPrice = 0;
            sumNoDiscount = 0;

            textBox_LogBookingNr.Clear();

            textBox_LogBookingNr.Clear();

            bindingSourceFreeConference.Clear();
            listBox1.DataSource = null;
            listBox3.DataSource = null;

            textBox_LogCoGuestNr.Clear();
            textBox_LogCoGuestNr.Enabled = true;
            textBox_LogCoOrgNr.Clear();
            textBox_LogCoOrgNr.Enabled = true;
            textBox_LogCoName.Clear();
            textBox_LogCoName.Enabled = true;
            textBox_LogCoAddress.Clear();
            textBox_LogCoZip.Clear();
            textBox_LogCoCity.Clear();
            textBox_LogCoReference.Clear();
            textBox_LogCoPhone.Clear();
            textBox_LogCoCredit.Clear();


            label_LogConfimation.Visible = false;

            if (checkBox_LogCancelProt.Checked == true)
            {
                checkBox_LogCancelProt.Checked = false;
            }
            timerFreeLodging.Enabled = false;
        }


        //************************************************************* Logiinfo lista ****************************************************//
        private void button_LogHideInfo_Click(object sender, EventArgs e) //Gömmer informationen
        {
            HideInfo();
        }

        private void button_LogShowInfo_Click(object sender, EventArgs e) //Visarinformationen
        {
            ShowInfo();
        }

        private void button_ConShowInfo_Click(object sender, EventArgs e)
        {
            ShowInfo();
        }

        private void button_ConHideInfo_Click(object sender, EventArgs e)
        {
            HideInfo();
        }

        /// <summary>
        /// Metod som gömmer logi och konferensinformationen
        /// </summary>
        private void HideInfo()
        {
            label_Log1Beds.Visible = false; label_Log1Rooms.Visible = false; label_Log1SqM.Visible = false;
            label_Log2Beds.Visible = false; label_Log2Rooms.Visible = false; label_Log2SqM.Visible = false;
            textBox_Log1Beds.Visible = false; textBox_Log1Rooms.Visible = false; textBox_Log1SqM.Visible = false;
            textBox_Log2Beds.Visible = false; textbox_Log2Rooms.Visible = false; textBox_Log2SqM.Visible = false;
            label_LogApart1.Visible = false; label_LogApart2.Visible = false;
            button_LogShowInfo.Show();
            button_LogHideInfo.Hide();
            label_LogInfo.Text = "Visa Information";
            label_ConBigInfo.Visible = false; label_ConBigNrRooms.Visible = false; label_ConBigSeats.Visible = false;
            label_ConSmallInfo.Visible = false; label_ConSmallNrRooms.Visible = false; label_ConSmallSeats.Visible = false;
            textBox_ConBigSeats.Visible = false; textBox_ConBigNrRooms.Visible = false;
            textbox_ConSmallSeats.Visible = false; textBox_ConSmallNrRooms.Visible = false;
            button_ConShowInfo.Show();
            button_ConHideInfo.Hide();
            label_ConInfo.Text = "Visa Information";

        }

        /// <summary>
        /// Metod som visar logi och konferensinformationen
        /// </summary>
        private void ShowInfo()
        {
            label_Log1Beds.Visible = true; label_Log1Rooms.Visible = true; label_Log1SqM.Visible = true;
            label_Log2Beds.Visible = true; label_Log2Rooms.Visible = true; label_Log2SqM.Visible = true;
            textBox_Log1Beds.Visible = true; textBox_Log1Rooms.Visible = true; textBox_Log1SqM.Visible = true;
            textBox_Log2Beds.Visible = true; textbox_Log2Rooms.Visible = true; textBox_Log2SqM.Visible = true;
            label_LogApart1.Visible = true; label_LogApart2.Visible = true;
            button_LogShowInfo.Hide();
            button_LogHideInfo.Show();
            label_LogInfo.Text = "Göm Information";
            label_ConBigInfo.Visible = true; label_ConBigNrRooms.Visible = true; label_ConBigSeats.Visible = true;
            label_ConSmallInfo.Visible = true; label_ConSmallNrRooms.Visible = true; label_ConSmallSeats.Visible = true;
            textBox_ConBigSeats.Visible = true; textBox_ConBigNrRooms.Visible = true;
            textbox_ConSmallSeats.Visible = true; textBox_ConSmallNrRooms.Visible = true;
            button_ConShowInfo.Hide();
            button_ConHideInfo.Show();
            label_ConInfo.Text = "Göm Information";
        }

        private void Lodging1Info() //Hämtar information om logityp 1 och visar i relevanta fält.
        {
            string tempLodg = "LGH I";
            currentLodging = LOGIC.LogicLodging.GetLodgingInfo(tempLodg);
            textBox_Log1Beds.Text = currentLodging.LodgingBeds;
            textBox_Log1Rooms.Text = currentLodging.LodgingRoom;
            textBox_Log1SqM.Text = currentLodging.LodgingSquarMeter;
        }

        private void Lodging2Info() //Hämtar information om logityp 2 och visar i relevanta fält.
        {
            string tempLodg = "LGH II";
            currentLodging = LOGIC.LogicLodging.GetLodgingInfo(tempLodg);
            textBox_Log2Beds.Text = currentLodging.LodgingBeds;
            textbox_Log2Rooms.Text = currentLodging.LodgingRoom;
            textBox_Log2SqM.Text = currentLodging.LodgingSquarMeter;
        }

        private void ConferenceBigInfo() //Hämtar information om konferensrum Storbacken
        {
            string tempConf = "Storbacken";
            currentConference = LOGIC.LogicConference.GetConferenceInfo(tempConf);
            textBox_ConBigSeats.Text = currentConference.ConferenceSeats;
            textBox_ConBigNrRooms.Text = currentConference.ConferenceNrOffRooms.ToString();
        }

        private void ConferenceSmallInfo()//Hämtar information om konferensrum Lillbacken
        {
            string tempConf = "Lillbacken";
            currentConference = LOGIC.LogicConference.GetConferenceInfo(tempConf);
            textbox_ConSmallSeats.Text = currentConference.ConferenceSeats;
            textBox_ConSmallNrRooms.Text = currentConference.ConferenceNrOffRooms.ToString();
        }


        private void buttonVisaLogi_Log_Click(object sender, EventArgs e)
        {
            button_LodgAdd.Enabled = true;
            button_LogSave.Enabled = false;
            bindingSourceFreeLodging.DataSource = null;
            
            
            ShowFreeLodgings();
          
        }

        private void timerCheckPrintTime_Tick(object sender, EventArgs e)
        {
            PrintInvoices();
        }

        /// <summary>
        /// Metod för att skriva ut fakturor 
        /// </summary>
        private void PrintInvoices()
        { string printTime = DateTime.Now.Date.AddHours(8).ToString();


        if ((Convert.ToDateTime(printTime).Hour == DateTime.Now.Date.Hour)) 
            {                                                               
         
               foreach (var i in invoice.GetInvoices())
                {                 
                   string selectedInvoice = i.ToString();
                   string[] invoiceDetails = selectedInvoice.Split('\t');

                    tempInvoiceID = int.Parse(invoiceDetails[1]);
                    tempBookingID = int.Parse(invoiceDetails[2]);
                    invoice.GetInvoice(tempBookingID);
                    if (invoiceDetails[0] == "a")
                    {
                        Invoice newInvoiceForm = new Invoice(invoice, tempInvoiceID, tempBookingID);
                        newInvoiceForm.Show();
                    }
                    else if (invoiceDetails[0] == "b")
                    {
                        BookingConfirmation newBookingConfirmationForm = new BookingConfirmation(invoice, tempInvoiceID, tempBookingID);
                      newBookingConfirmationForm.ShowDialog();
                    }

                    else if (invoiceDetails[0] == "c")
                    {
                        Invoice newInvoiceForm = new Invoice(invoice, tempInvoiceID, tempBookingID);

                    }
                }
            }
            else
            {
              
            }
        }

        private void timerFreeLodging_Tick(object sender, EventArgs e)
        {
            ShowFreeLodgings();
        } 

        /// <summary>
        /// Metod som hämtar in de lediga logialternativen för den valda veckan och perioden.
        /// </summary>
        private void ShowFreeLodgings()
        {
            try
            {
                DateTime endDate = Convert.ToDateTime(dateTimeSlutDat_Log.Text);
                DateTime startdate = Convert.ToDateTime(dateTimeStartDat_Log.Text);
                string period = comboBoxPeriod_Log.Text;

                if (comboBoxPeriod_Log.Text == "Sön-fre")
                {
                    period = "5";
                }
                else if (comboBoxPeriod_Log.Text == "Fre-sön")
                {
                    period = "2";
                }
                else
                    period = "7";


                if (endDate == startdate || endDate < startdate)
                {
                    MessageBox.Show("Felaktigt bokningsintervall, du måste boka logi minst en dag");
                }

                else
                {
                    bindingSourcePris.DataSource = currentLodging.GetPrice(int.Parse(comboBoxLodgWeekNr.Text), period);
                    bindingSourceFreeLodging.DataSource = currentLodging.GetApartmentFreeLodging(startdate, endDate, comboBoxLodgWeekNr.Text);

                    if (bindingSourceFreeLodging.DataSource == null)
                        MessageBox.Show("Inga lediga logier kunde hittas för de angivna datumen.");

                    else
                        button_LogSave.Enabled = true;
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Något gick dessvärre fel, error:" + ex);
            }
        }

        private void dateTimeStartDat_Log_ValueChanged(object sender, EventArgs e)
        {
            //DateTime date = dateTimeStartDat_Log.Value.Date;
            //int week = currentLodging.WeekNrFromDate(date);

            //comboBoxCampWeekNr.Text = week.ToString();
            //comboBoxLodgWeekNr.Text = week.ToString();
            //comboBoxConfWeek.Text = week.ToString();

        }

        private void button_LogRemove_Click(object sender, EventArgs e)
        {
            if (listBox_LogReserved.SelectedIndex == -1)
            {
                MessageBox.Show("Du måste markera det val du vill ta bort");
            }
            else
            {                
                decimal tempPrice = 0;
                decimal totPrice = sumNoDiscount;
                decimal noVat = decimal.Parse(textBox_LogSumNoVat.Text);
                decimal vat = decimal.Parse(textBox_LogVat.Text);
                string bookingDetails = listBox_LogReserved.SelectedItem.ToString();
                string[] bookingDetailsSplit = bookingDetails.Split('\t');
                tempPrice = int.Parse(bookingDetailsSplit[2]);
                totPrice -= tempPrice;
                sumNoDiscount -= tempPrice;
                noVat -= ((decimal)tempPrice * (decimal)0.88);
                vat -= ((decimal)tempPrice * (decimal)0.12);
                textBox_LogTotalSum.Text = totPrice.ToString();
                textBox_LogSumNoVat.Text = noVat.ToString();
                textBox_LogVat.Text = vat.ToString();

                string rentDetails;
                string[] rentDetailsSplit;
                string lodgingId;
                DateTime startDate;
                DateTime stopDate;
            

                  if (button_LogSave.Enabled == true && listBox_LogReserved.SelectedItem.ToString() != "")
                  {
                    rentDetails = listBox_LogReserved.SelectedItem.ToString();
                        rentDetailsSplit = rentDetails.Split('\t', '\t', '\t', '\t', '\t','\t');

                        lodgingId = rentDetailsSplit[0];
                        startDate = Convert.ToDateTime(rentDetailsSplit[4]);
                        stopDate = Convert.ToDateTime(rentDetailsSplit[5]);
                        LOGIC.LogicBooking.DropReservedLodging(lodgingId, startDate, stopDate);  
                  }


                

                if (listBox_LogReserved.DataSource == null)
                {
                    if (listBox_LogReserved.Items.Count == 1)
                    {
                        listBox_LogReserved.Items.Clear();
                    }
                    else
                    {
                        listBox_LogReserved.Items.RemoveAt(listBox_LogReserved.SelectedIndex);
                    }
                }                
                else
                {
                    listBox_LogReserved.DataSource = null;
                }     
            }
        }

        /// <summary>
        /// Tar bort reserverade logi från reservations tabellen med vissa villkor 
        /// </summary>
        public void DropReserveTable()
        {
            try
            {
                string rentDetails;
                string[] rentDetailsSplit;
                string lodgingId;
                DateTime startDate;
                DateTime stopDate;


                if (listBox_LogReserved.SelectedIndex == -1)
                {
                    for (int i = 0; i < listBox_LogReserved.Items.Count; i++)
                    {
                        rentDetails = listBox_LogReserved.Items[i].ToString();
                        rentDetailsSplit = rentDetails.Split('\t', '\t', '\t', '\t', '\t');

                        lodgingId = rentDetailsSplit[0];
                        startDate = Convert.ToDateTime(rentDetailsSplit[4]);
                        stopDate = Convert.ToDateTime(rentDetailsSplit[5]);
                        LOGIC.LogicBooking.DropReservedLodging(lodgingId, startDate, stopDate);
                    }

                }

                else
                    for (int i = 0; i < listBox_LogReserved.Items.Count; i++)
                    {
                        rentDetails = listBox_LogReserved.Items[i].ToString();
                        rentDetailsSplit = rentDetails.Split('\t', '\t', '\t', '\t', '\t');

                        lodgingId = rentDetailsSplit[0];
                        startDate = Convert.ToDateTime(rentDetailsSplit[4]);
                        stopDate = Convert.ToDateTime(rentDetailsSplit[5]);
                        LOGIC.LogicBooking.DropReservedLodging(lodgingId, startDate, stopDate);
                    }
            }
            catch (Exception)
            {
                MessageBox.Show("Du måste markera den logi du vill ta bort");
            }
        }

        private void button_LogAdd_Click(object sender, EventArgs e)
        {
            try
            {
                string text;        
                               

                DateTime endDate = Convert.ToDateTime(dateTimeSlutDat_Log.Text);
                DateTime startDate = Convert.ToDateTime(dateTimeStartDat_Log.Text);
                string lodgingType = dataGridView_LogFree.CurrentRow.Cells[0].Value.ToString();

                string lodgingid = currentLodging.GetLodgingID(startDate, endDate, lodgingType)[0];

                text = "\t" + dataGridView_LogFree.CurrentRow.Cells[0].Value.ToString()
                    + "\t" + dataGridView_LogFree.CurrentRow.Cells[2].Value.ToString()
                    + "\t" + dataGridView_LogFree.CurrentRow.Cells[3].Value.ToString()
                    + "\t" + dateTimeStartDat_Log.Value.ToShortDateString()
                    + "\t" + dateTimeSlutDat_Log.Value.ToShortDateString();

                

                if (textBox_LogPrCredit.Text == string.Empty || textBox_LogPrCredit.Text == "") //*
                {
                    if (listBox_LogReserved.DataSource != null)
                    {
                        listBox_LogReserved.DataSource = null;
                        listBox_LogReserved.Items.Add(lodgingid + text);

                        LOGIC.LogicBooking.ShoppingCart(lodgingid, startDate, endDate);
                        BookingPrice(dataGridView_LogFree.CurrentRow.Cells[2].Value.ToString());
                    }
                    else
                    {
                        listBox_LogReserved.Items.Add(lodgingid + text);

                        LOGIC.LogicBooking.ShoppingCart(lodgingid, startDate, endDate);
                        BookingPrice(dataGridView_LogFree.CurrentRow.Cells[2].Value.ToString());
                    }
                                       
                }
                else
                {
                    decimal totPrice = decimal.Parse(textBox_LogTotalSum.Text);

                    decimal credit = decimal.Parse(textBox_LogPrCredit.Text);
                    
                    decimal pris = decimal.Parse(dataGridView_LogFree.CurrentRow.Cells[2].Value.ToString());

                    decimal currentPrice = pris + totPrice;

                    if (currentPrice > credit)
                    {                 
                        DialogResult rusultat = MessageBox.Show("Gästen överskrider kreditgränsen! \nGästens kredit är för låg för den aktuella bokningen", "Viktigt", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else if (listBox_LogReserved.DataSource == null)
                    {
                        listBox_LogReserved.DataSource = null;
                        listBox_LogReserved.Items.Add(lodgingid + text);

                        LOGIC.LogicBooking.ShoppingCart(lodgingid, startDate, endDate);
                        BookingPrice(dataGridView_LogFree.CurrentRow.Cells[2].Value.ToString());
                    }
                    else
                    {
                        listBox_LogReserved.Items.Add(lodgingid + text);

                        LOGIC.LogicBooking.ShoppingCart(lodgingid, startDate, endDate);
                        BookingPrice(dataGridView_LogFree.CurrentRow.Cells[2].Value.ToString());
                    }
                    
                }                
                
            }
            catch 
            {
                DialogResult result = MessageBox.Show("Det finns inga logier kvar av den typen.", "Viktigt", MessageBoxButtons.OK, MessageBoxIcon.Hand); 
            }

            timerFreeLodging.Enabled = true;
            timerCheckingPrintTime.Enabled = true;
        }
        
        /// <summary>
        /// Lägger ihop och räknar ut totala beloppet, momsen samt beloppet utan moms.
        /// </summary>
        private void BookingPrice(string price)
        {
            decimal tempPrice = 0;
            decimal logTotPrice = sumNoDiscount;
            decimal noVat = 0;
            decimal vat = 0;
            decimal discount = 0;
            tempPrice = decimal.Parse(price);
            logTotPrice += tempPrice;
            sumNoDiscount += tempPrice;
            noVat = ((decimal)logTotPrice * (decimal)0.88);
            vat = ((decimal)logTotPrice - (decimal)noVat);
            textBox_LogTotalSum.Text = logTotPrice.ToString();

            if (textBox_LogDiscount.Text != "" && textBox_LogDiscount.Text != "0")
            {
                discount = decimal.Parse(textBox_LogDiscount.Text);
                discount = (1 - ((decimal.Parse(textBox_LogDiscount.Text) / 100)));
                if (checkBox_LogCancelProt.Checked)
                {
                    logTotPrice = decimal.Parse(textBox_LogTotalSum.Text);
                    logTotPrice -= decimal.Parse(textBox_LogCancelProt.Text);
                    logTotPrice = (decimal)(logTotPrice * discount);
                    logTotPrice += decimal.Parse(textBox_LogCancelProt.Text);
                    noVat = ((decimal)logTotPrice * (decimal)0.88);
                    vat = ((decimal)logTotPrice - (decimal)noVat);
                }
                else
                {
                    logTotPrice = (decimal)(logTotPrice * discount);
                    noVat = ((decimal)logTotPrice * (decimal)0.88);
                    vat = ((decimal)logTotPrice - (decimal)noVat);
                }
            }

            textBox_LogTotalSum.Text = Convert.ToInt32(logTotPrice).ToString();
            textBox_LogSumNoVat.Text = noVat.ToString();
            textBox_LogVat.Text = vat.ToString();
        }

        /// <summary>
        /// Justerar priset om rabattsatsen ändras
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_LogDiscount_TextChanged(object sender, EventArgs e)
        {
            decimal discount;
            decimal noVat = decimal.Parse(textBox_LogSumNoVat.Text);
            decimal vat = decimal.Parse(textBox_LogVat.Text);
            if (decimal.Parse(textBox_LogTotalSum.Text) != 0)
            {
                
                if (textBox_LogDiscount.Text != "" && textBox_LogDiscount.Text != "0")
                {
                    if (errorhand.OnlyNumbers(textBox_LogDiscount.Text) == false)
                    {
                        MessageBox.Show("Rabatten får enbart innehålla siffror");
                    }
                    else
                    {
                        discount = (1 - ((decimal.Parse(textBox_LogDiscount.Text) / 100)));
                        if (checkBox_LogCancelProt.Checked)
                        {
                            logTotPrice = sumNoDiscount;
                            logTotPrice -= decimal.Parse(textBox_LogCancelProt.Text);
                            logTotPrice = ((decimal)logTotPrice * (decimal)discount);
                            logTotPrice += decimal.Parse(textBox_LogCancelProt.Text);
                            noVat = ((decimal)logTotPrice * (decimal)0.88);
                            vat = ((decimal)logTotPrice - (decimal)noVat);
                        }
                        else
                        {
                            logTotPrice = sumNoDiscount;
                            logTotPrice = (int)((decimal)logTotPrice * (decimal)discount);
                        }
                    }
                }
                else
                {
                    discount = 0;
                    logTotPrice = sumNoDiscount;
                    noVat = ((decimal)logTotPrice * (decimal)0.88);
                    vat = ((decimal)logTotPrice - (decimal)noVat);
                }
                textBox_LogTotalSum.Text = Convert.ToInt32(logTotPrice).ToString();
                textBox_LogSumNoVat.Text = Convert.ToInt32(noVat).ToString();
                textBox_LogVat.Text = Convert.ToInt32(vat).ToString();
            }
        }


        /// <summary>
        /// Lägger till eller tar bort avbeställningsskyddskostnaden till totalpriset, momsen samt beloppet utan moms.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox_LogCancelProt_CheckedChanged(object sender, EventArgs e)
        {
            logTotPrice = decimal.Parse(textBox_LogTotalSum.Text);
            decimal noVat = decimal.Parse(textBox_LogSumNoVat.Text);
            decimal vat = decimal.Parse(textBox_LogVat.Text);

            if (checkBox_LogCancelProt.Checked)
            {
                textBox_LogCancelProt.Text = "250";
                decimal cancelProt = decimal.Parse(textBox_LogCancelProt.Text);
                logTotPrice += cancelProt;
                sumNoDiscount += cancelProt;
                noVat += ((decimal)cancelProt * (decimal)0.88);
                vat += ((decimal)cancelProt * (decimal)0.12);
            }
            else
            {
                decimal cancelProt = decimal.Parse(textBox_LogCancelProt.Text);
                logTotPrice -= cancelProt;
                sumNoDiscount -= cancelProt;
                noVat -= ((decimal)cancelProt * (decimal)0.88);
                vat -= ((decimal)cancelProt * (decimal)0.12);
                textBox_LogCancelProt.Text = "0";
            }

            textBox_LogTotalSum.Text = Convert.ToInt32(logTotPrice).ToString();
            textBox_LogSumNoVat.Text = Convert.ToInt32(noVat).ToString();
            textBox_LogVat.Text = Convert.ToInt32(vat).ToString();
        }


        private void buttonSparaGäst_Log_Click(object sender, EventArgs e)
        {
            SaveGuestPr_or_Co();          
        }

        private void buttonSparaGästCo_Click(object sender, EventArgs e)
        {
            SaveGuestPr_or_Co();       

        }

        /// <summary>
        /// Metod som sparar en ny gäst
        /// </summary>
        private void SaveGuestPr_or_Co()
        {
            if (tabControl_LogGuest.SelectedIndex == 0) //Kontrollerar om det är en privatperson som skall sparas
            {
                if (errorhand.OnlyLetters(textBox_LogPrFName.Text.Trim()) == false)
                    MessageBox.Show("Fyll i förnamn, Förnamn får endast innehålla bokstäver");
                else if (errorhand.OnlyLetters(textBox_LogPrLName.Text.Trim()) == false)
                    MessageBox.Show("Fyll i efternamn, Efternamn får endast innehålla bokstäver");
                else if (textBox_LogPrAddress.Text == "")
                    MessageBox.Show("Du måste ange gatuadress");
                else if (errorhand.OnlyNumbers(textBox_LogPrZip.Text.Trim()) == false)
                    MessageBox.Show("Du måste ange postnr, Postnr får endast innehålla siffror");
                else if (errorhand.OnlyLetters(textBox_LogPrCity.Text.Trim()) == false)
                    MessageBox.Show("Orten får endast innehålla bokstäver");
                
                else if (errorhand.OnlyNumbers(textBox_LogPrPhone.Text.Trim()) == false)
                    MessageBox.Show("Telefonnummer får endast innehålla siffor");
                else if (textBox_LogPrGuestNr.Text != "") //Kontrollerar om det är en redan befintlig gäst som skall sparas genom att se om det finns ett gästnummer ifyllt
                {
                    LOGIC.LogicPrivateGuest.ChangedPrGuest(int.Parse(textBox_LogPrGuestNr.Text), textBox_LogPrFName.Text.Trim(), textBox_LogPrLName.Text.Trim(), textBox_LogPrAddress.Text.Trim(), textBox_LogPrZip.Text.Trim(), textBox_LogPrCity.Text.Trim(), textBox_LogPrPhone.Text.Trim());
                    textBox_LogPrFName.Enabled = false;
                    textBox_LogPrLName.Enabled = false;
                    textBox_LogPrAddress.Enabled = false;
                    textBox_LogPrZip.Enabled = false;
                    textBox_LogPrCity.Enabled = false;
                    textBox_LogPrPhone.Enabled = false;
                    buttonSparaGäst_Log.Visible = false;
                }
                else
                {
                    privateGuest = LOGIC.LogicPrivateGuest.NewPrivateGuest(textBox_LogPrFName.Text.Trim(), textBox_LogPrLName.Text.Trim(), textBox_LogPrAddress.Text.Trim(), textBox_LogPrZip.Text.Trim(), textBox_LogPrCity.Text.Trim(), textBox_LogPrPhone.Text.Trim(), int.Parse(textBox_LogPrCredit.Text), 0);
                    buttonSparaGäst_Log.Visible = false;
                    int guestNr = guest.GetGuestNr();
                    textBox_LogPrGuestNr.Text = "" + guestNr;

                    textBox_LogPrFName.Enabled = false;
                    textBox_LogPrLName.Enabled = false;
                    textBox_LogPrAddress.Enabled = false;
                    textBox_LogPrZip.Enabled = false;
                    textBox_LogPrCity.Enabled = false;
                    textBox_LogPrPhone.Enabled = false;
                }
            }
            if (tabControl_LogGuest.SelectedIndex == 1)//Kontrollerar om det är en företagsgäst som skall sparas
            {
                if (textBox_LogCoOrgNr.Text == "")
                    MessageBox.Show("Du måste ange ett organisationsnummer");
                else if (textBox_LogCoName.Text == "")
                    MessageBox.Show("Du måste ange ett företagsnamn");
                else if (textBox_LogCoReference.Text == "")
                    MessageBox.Show("Du måste ange en referens");
                else if (textBox_LogCoAddress.Text == "")
                    MessageBox.Show("Du måste fylla i en gatuadress");
                else if (errorhand.OnlyNumbers(textBox_LogCoZip.Text.Trim()) == false)
                    MessageBox.Show("Fyll i postnummer, Postnummer får enbart innehålla siffror");
                else if (errorhand.OnlyLetters(textBox_LogCoCity.Text.Trim()) == false)
                    MessageBox.Show("Orten får enbart innehålla bokstäver");                
                else if (errorhand.OnlyNumbers(textBox_LogCoPhone.Text.Trim()) == false)
                    MessageBox.Show("Telefonnummer får enbart innehålla siffor");
                else if (textBox_LogCoGuestNr.Text != "")//Kontrollerar om det redan är en befinlig företagsgäst som skall sparas genom att se om det redan finns ett gästnummer.
                {
                    LOGIC.LogicCompanyGuest.ChangedCoGuest(int.Parse(textBox_LogCoGuestNr.Text), textBox_LogCoOrgNr.Text.Trim(), textBox_LogCoName.Text.Trim(), textBox_LogCoReference.Text.Trim(), textBox_LogCoAddress.Text.Trim(), textBox_LogCoZip.Text.Trim(), textBox_LogCoCity.Text.Trim(), textBox_LogCoPhone.Text.Trim());
                    textBox_LogCoReference.Enabled = false;
                    textBox_LogCoAddress.Enabled = false;
                    textBox_LogCoZip.Enabled = false;
                    textBox_LogCoCity.Enabled = false;
                    textBox_LogCoPhone.Enabled = false;
                    textBox_LogCoCredit.Enabled = false;
                    textBox_LogCoGuestNr.Enabled = false;
                    buttonSparaGästCo.Visible = false;
                }
                else
                {
                    companyGuest = LOGIC.LogicCompanyGuest.NewCompanyGuest(textBox_LogCoOrgNr.Text.Trim(), textBox_LogCoName.Text.Trim(), textBox_LogCoReference.Text.Trim(), textBox_LogCoAddress.Text.Trim(), textBox_LogCoZip.Text.Trim(), textBox_LogCoCity.Text.Trim(), textBox_LogCoPhone.Text.Trim(), int.Parse(textBox_LogCoCredit.Text.Trim()));
                    buttonSparaGästCo.Visible = false;

                    int guestNr = guest.GetGuestNr();
                    textBox_LogCoGuestNr.Text = "" + guestNr;

                    textBox_LogCoReference.Enabled = false;
                    textBox_LogCoAddress.Enabled = false;
                    textBox_LogCoZip.Enabled = false;
                    textBox_LogCoCity.Enabled = false;
                    textBox_LogCoPhone.Enabled = false;
                    textBox_LogCoCredit.Enabled = false;
                    textBox_LogCoGuestNr.Enabled = true;
                }
            }
        }

        private void comboBoxPeriod_Log_SelectedIndexChanged(object sender, EventArgs e)
        {
            SearchLodging();
            button_LodgAdd.Enabled = false;
        }
        private void comboBoxWeckoNr_Log_SelectedIndexChanged(object sender, EventArgs e)
        {
            SearchLodging();
            button_LodgAdd.Enabled = false;
        }

        /// <summary>
        /// Visar rätt datum för den vecka samt period som väljs i logibokningsdelen
        /// </summary>
        public void SearchLodging()
        {
            int year = DateTime.Now.Year;
            int addWeek = 0;
            DayOfWeek startDay;
            DayOfWeek stopDay;
           
            if (int.Parse(comboBoxLodgWeekNr.Text) < currentLodging.WeekNrFromDate(DateTime.Now.Date))
            {
                year++;
            }
            if (comboBoxPeriod_Log.Text == "Sön-fre")
            {
                startDay = DayOfWeek.Sunday;
                stopDay = DayOfWeek.Friday;
            }
            else if (comboBoxPeriod_Log.Text == "Fre-sön")
            {
                startDay = DayOfWeek.Friday;
                stopDay = DayOfWeek.Sunday;
                addWeek = 1;
            }
            else
            {
                startDay = DayOfWeek.Sunday;
                stopDay = DayOfWeek.Sunday; addWeek = 1;
            }
            dateTimeStartDat_Log.Text = currentLodging.WeeknrToDate(year,int.Parse(comboBoxLodgWeekNr.Text), startDay).ToShortDateString();
            dateTimeSlutDat_Log.Text = currentLodging.WeeknrToDate(year, int.Parse(comboBoxLodgWeekNr.Text) + addWeek, stopDay).ToShortDateString();            
        }

        /// <summary>
        /// Visar rätt datum för den vecka samt period som väljs i campingbokningsdelen
        /// </summary>
        private void SearchCamp()
        {
            int year = DateTime.Now.Year;
            int addWeek = 0;
            DayOfWeek startDay = DayOfWeek.Sunday;
            DayOfWeek stopDay = DayOfWeek.Sunday; addWeek = 1;
            if (int.Parse(comboBoxCampWeekNr.Text) < currentLodging.WeekNrFromDate(DateTime.Now.Date))
            {
                year++;
            }

            dateTimePicker_CampDateFrom.Text = currentLodging.WeeknrToDate(year, int.Parse(comboBoxCampWeekNr.Text), startDay).ToShortDateString();

            dateTimePicker_CampDateTo.Text = currentLodging.WeeknrToDate(year, int.Parse(comboBoxCampWeekNr.Text) + addWeek, stopDay).ToShortDateString();
        }

        /// <summary>
        /// Visar rätt datum för den vecka samt period som väljs i konferensbokningsdelen
        /// </summary>
        private void SearchConference()
        {
            int year = DateTime.Now.Year;
            int addWeek = 0;
            DayOfWeek startDay = DayOfWeek.Sunday;
            DayOfWeek stopDay = DayOfWeek.Sunday; addWeek = 1;
            if (int.Parse(comboBoxConfWeek.Text) < currentLodging.WeekNrFromDate(DateTime.Now.Date))
            {
                year++;
            }

            dateTimePicker_ConfDateFrom.Text = currentLodging.WeeknrToDate(year, int.Parse(comboBoxConfWeek.Text), startDay).ToShortDateString();

            dateTimePicker_ConfDateTo.Text = currentLodging.WeeknrToDate(year, int.Parse(comboBoxConfWeek.Text) + addWeek, stopDay).ToShortDateString();
        }
        //********************************************************************************* Huvudmeny funktioner *****************************************************************************//
        #region
        /// <summary>
        /// Avslutar programmet
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        private void avslutaToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            DialogResult result;
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            result = MessageBox.Show("Är du säker på att du vill avsluta?", "Viktigt", buttons);
            if (result == DialogResult.Yes)
            { Application.Exit(); }
        }

        /// <summary>
        /// Stänger fönstrena och öppnar inloggningen.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void avslutaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            // Detta fungerar inte då fönstret ligger kvar i bakgrunden.... någon som kan fixa... snälla gör det :
            DialogResult result;
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            result = MessageBox.Show("Är du säker på att du vill logga ut?" , "Viktigt", buttons);
            if (result == DialogResult.Yes)
            {
                this.Close();
                if (Application.OpenForms.OfType<CLRS_Inloggning>().Count() == 0)
                {
                    CLRS_Inloggning loadInlog = new CLRS_Inloggning();
                    loadInlog.ShowDialog();
                }
            }            
         }

        /// <summary>
        /// Öppnar Skidshopsfönstret
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skidshopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Application.OpenForms.OfType<Skishop>().Count() == 0)
            {
                Skishop loadSkishop = new Skishop();
                loadSkishop.ShowDialog();
            }
            else
            {
                MessageBox.Show("Fönstret är redan öppet");
            }
        }

        /// <summary>
        /// Öppnar Administrationen
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void adminToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Application.OpenForms.OfType<Admin>().Count() == 0)
            {
                Admin loadAdmin = new Admin();
                loadAdmin.ShowDialog();
            }
            else
            {
                MessageBox.Show("Fönstret är redan öppet");
            }
        }


        #endregion
        //*************************************************************************** Visa/Redigera bokning ***********************************************************************//

        private void HideThings()//Metod för att inte visa eller disabla saker vid uppstart, måste läggas in i 
        {
            comboBox_LogAlt.Enabled = false;
            textBox_LogSearch.Enabled = false; 
        }

        private void radioButtonPrGuestSearch_CheckedChanged(object sender, EventArgs e)
        {
            listBox_LogBookingList.DataSource = null;
            listBox_LogBookingRows.DataSource = null;

            if (!comboBox_LogAlt.Items.Contains("BokningsNr-Privat"))
            {
                comboBox_LogAlt.Items.Clear();

                comboBox_LogAlt.Items.Add("BokningsNr-Privat");
                comboBox_LogAlt.Items.Add("GästNr");
                comboBox_LogAlt.Items.Add("Förnamn/Efternamn");
                //comboBox_LogAlt.Items.Add("Efternamn");
                comboBox_LogAlt.Enabled = true;
                textBox_LogSearch.Enabled = true;
                radioButtonCoGuestSearch.Checked = false;
            }
        }

        private void radioButtonCoGuestSearch_CheckedChanged(object sender, EventArgs e)
        {
            listBox_LogBookingList.DataSource = null;
            listBox_LogBookingRows.DataSource = null;

            if (!comboBox_LogAlt.Items.Contains("BokningsNr-Företag"))
            {
                comboBox_LogAlt.Items.Clear();

                comboBox_LogAlt.Items.Add("BokningsNr-Företag");
                comboBox_LogAlt.Items.Add("GästNr");
                comboBox_LogAlt.Items.Add("Företag");
                comboBox_LogAlt.Enabled = true;
                textBox_LogSearch.Enabled = true;
                radioButtonPrGuestSearch.Checked = false;
            }
        }


        private void button_LogSearch_Click_1(object sender, EventArgs e)
        {            
            try
            {
                if (radioButtonPrGuestSearch.Checked)//(comboBox_LogAlt.SelectedIndex == 0)
                {  
                    try
                    {
                        if (comboBox_LogAlt.SelectedIndex == 0)
                        {
                            try
                            {
                                int tempId = int.Parse(textBox_LogSearch.Text);
                                listBox_LogBookingList.DataSource = currentBooking.GetBookingById(tempId);
                            }
                            catch
                            {
                                DialogResult rusultat = MessageBox.Show("Bokningsnummer finns ej", "Viktigt", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }                              
                        }
                        else if (comboBox_LogAlt.SelectedIndex == 1)
                        {
                            int tempPrGuestId = int.Parse(textBox_LogSearch.Text);
                            listBox_LogBookingList.DataSource = currentBooking.GetBookingByPrGuestId(tempPrGuestId);
                        }
                        else if (comboBox_LogAlt.SelectedIndex == 2)
                        {
                            string tempName = textBox_LogSearch.Text.Trim();
                            tempName = tempName.Replace(" ", "");
                            listBox_LogBookingList.DataSource = currentBooking.GetBookingByName(tempName);
                        }
    
                    }
                    catch
                    {
                        DialogResult rusultat = MessageBox.Show("Skriv ett sökord i sökfältet", "Viktigt", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                   
                }
                else if (radioButtonCoGuestSearch.Checked)
                {
                    try
                    {
                        if (comboBox_LogAlt.SelectedIndex == 0)
                        {
                            int tempId = int.Parse(textBox_LogSearch.Text);
                            listBox_LogBookingList.DataSource = currentBooking.GetBookingByIdCompany(tempId);
                        }
                    
                        else if (comboBox_LogAlt.SelectedIndex == 1)
                        {
                            int tempCoGuestId = int.Parse(textBox_LogSearch.Text);
                            listBox_LogBookingList.DataSource = currentBooking.GetBookingByCoGuestId(tempCoGuestId);
                        }
                        else if (comboBox_LogAlt.SelectedIndex == 2)
                        {
                            string tempCoGuestName = textBox_LogSearch.Text;
                            listBox_LogBookingList.DataSource = currentBooking.GetBookingByCoName(tempCoGuestName);
                        }

                    }
                    catch
                    {
                        DialogResult rusultat = MessageBox.Show("Skriv ett sökord i sökfältet", "Viktigt", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
 
                }             
                
            }
            catch
            {
                DialogResult rusultat = MessageBox.Show("Du måste skriva något i sökrutan", "Viktigt", MessageBoxButtons.OK, MessageBoxIcon.Information); 
            }
        }

        /// <summary>
        /// Visa bokningsrader för vald bokning
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_LogInfo2_Click(object sender, EventArgs e)
        {
            if (listBox_LogBookingList.Items.Count > 0)
            {
                listBox_LogBookingRows.Visible = true;
                string choosenBooking = listBox_LogBookingList.SelectedItem.ToString() + ", ";
                string[] choosenBookingSplit = choosenBooking.Split(' ');
                int tempBookingId = int.Parse(choosenBookingSplit[0]);
                listBox_LogBookingRows.DataSource = currentBooking.GetBookingRows(tempBookingId);
            }
        }

        private void button_LogRemove2_Click(object sender, EventArgs e) // ta bort sökt bokning från databasen
        {
            DialogResult result;
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            result = MessageBox.Show("Är du säker på att du vill ta bort bokningen?" , "Viktigt", buttons);
            if (result == DialogResult.Yes)
            {
                try
                {
                    string rentDetails;
                    string[] rentDetailsSplit;
                    int bokningsNr;
                    int guestNr;

                    rentDetails = listBox_LogBookingList.SelectedItem.ToString();
                    rentDetailsSplit = rentDetails.Split(' ', ' ', ' ');

                    bokningsNr = int.Parse(rentDetailsSplit[0]);
                    guestNr = int.Parse(rentDetailsSplit[1]);
                    LOGIC.LogicGuest.UpdateGuestCredit(guestNr, bokningsNr);
                    
                    LOGIC.LogicBooking.DropBookingLodging(bokningsNr);
                    
                    listBox_LogBookingList.DataSource = null;
                    listBox_LogBookingRows.DataSource = null; //tar bort den markerade i listan men gömmer resten så man måste söka igen. Tillfällig lösning                
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ett fel uppstod" + ex);
                }
            }           
        }

        private void button_LogShowChange_Click(object sender, EventArgs e)
        {

            if (listBox_LogBookingList.SelectedIndex == -1)
            {
                MessageBox.Show("Du måste markera den som du vill ändra");
            }

            else
            {

                string rentDetails = listBox_LogBookingList.SelectedItem.ToString();

                string[] rentDetailsSplit = rentDetails.Split(' ');

                int guestNr = int.Parse(rentDetailsSplit[1]);

                string choosenBooking = listBox_LogBookingList.SelectedItem.ToString();

                string[] choosenBookingSplit = choosenBooking.Split(' ');

                int bokningsNr = int.Parse(choosenBookingSplit[0]);

                try
                {
                    if (radioButtonCoGuestSearch.Checked == true)
                    {

                        tabControl_Log.SelectedTab = tabPage1;
                        tabControl_LogGuest.SelectedTab = Företag;

                        dataGridViewCoGuest.DataSource = companyGuest.GetCoGuestById(guestNr);

                        textBox_LogCoOrgNr.Text = dataGridViewCoGuest.CurrentRow.Cells[0].Value.ToString();
                        textBox_LogCoName.Text = dataGridViewCoGuest.CurrentRow.Cells[1].Value.ToString();
                        textBox_LogCoReference.Text = dataGridViewCoGuest.CurrentRow.Cells[2].Value.ToString();
                        textBox_LogCoAddress.Text = dataGridViewCoGuest.CurrentRow.Cells[3].Value.ToString();
                        textBox_LogCoZip.Text = dataGridViewCoGuest.CurrentRow.Cells[4].Value.ToString();
                        textBox_LogCoCity.Text = dataGridViewCoGuest.CurrentRow.Cells[5].Value.ToString();
                        textBox_LogCoPhone.Text = dataGridViewCoGuest.CurrentRow.Cells[6].Value.ToString();
                        textBox_LogCoCredit.Text = dataGridViewCoGuest.CurrentRow.Cells[7].Value.ToString();
                        textBox_LogCoGuestNr.Text = dataGridViewCoGuest.CurrentRow.Cells[8].Value.ToString();
                        textBox_LogDiscount.Text = dataGridViewCoGuest.CurrentRow.Cells[9].Value.ToString();
                        textBox_LogCoGuestNr.Enabled = false;
                        textBox_LogCoOrgNr.Enabled = false;
                        textBox_LogCoName.Enabled = false;
                        
                        for (int i = 0; i < currentBooking.GetBookingRows(bokningsNr).Count; i++)
                        {
                            listBox_LogReserved.Items.Add(currentBooking.GetBookingRows(bokningsNr)[i]);
                        }

                        LOGIC.LogicGuest.UpdateGuestCredit(guestNr, bokningsNr);
                        LOGIC.LogicInvoice.SetNullBookingIDForInvoice(guestNr);
                        LOGIC.LogicBooking.DropBookingLodging(bokningsNr);

                        string choosenPrice;
                        string[] choosenPriceSplit;

                        for (int i = 0; i < listBox_LogReserved.Items.Count; i++)
                        {
                            choosenPrice = listBox_LogReserved.Items[i].ToString();
                            choosenPriceSplit = choosenPrice.Split('\t', '\t', '\t', '\t', '\t');

                            int pris = int.Parse(choosenPriceSplit[2]);
                            string lodgingid = choosenPriceSplit[0].ToString();
                            DateTime startDate = Convert.ToDateTime(choosenPriceSplit[4]);
                            DateTime endDate = Convert.ToDateTime(choosenPriceSplit[5]);


                            BookingPrice(pris.ToString());

                            LOGIC.LogicBooking.ShoppingCart(lodgingid, startDate, endDate);
                        }
                    }
                    else if (radioButtonPrGuestSearch.Checked == true)
                    {
                        tabControl_Log.SelectedTab = tabPage1;
                        tabControl_LogGuest.SelectedTab = Privat;

                        dataGridViewPGuest.DataSource = privateGuest.GetGuestById(guestNr);

                        textBox_LogPrGuestNr.Text = dataGridViewPGuest.CurrentRow.Cells[7].Value.ToString();
                        textBox_LogPrFName.Text = dataGridViewPGuest.CurrentRow.Cells[0].Value.ToString();
                        textBox_LogPrLName.Text = dataGridViewPGuest.CurrentRow.Cells[1].Value.ToString();
                        textBox_LogPrAddress.Text = dataGridViewPGuest.CurrentRow.Cells[2].Value.ToString();
                        textBox_LogPrCity.Text = dataGridViewPGuest.CurrentRow.Cells[4].Value.ToString();
                        textBox_LogPrZip.Text = dataGridViewPGuest.CurrentRow.Cells[3].Value.ToString();
                        textBox_LogPrPhone.Text = dataGridViewPGuest.CurrentRow.Cells[5].Value.ToString();
                        textBox_LogPrCredit.Text = dataGridViewPGuest.CurrentRow.Cells[6].Value.ToString();
                        textBox_LogDiscount.Text = dataGridViewPGuest.CurrentRow.Cells[8].Value.ToString();
                        textBox_LogPrGuestNr.Enabled = false;
                        textBox_LogPrFName.Enabled = false;
                        textBox_LogPrLName.Enabled = false;


                        for (int i = 0; i < currentBooking.GetBookingRows(bokningsNr).Count; i++)
                        {
                            listBox_LogReserved.Items.Add(currentBooking.GetBookingRows(bokningsNr)[i]);
                        }

                        LOGIC.LogicGuest.UpdateGuestCredit(guestNr, bokningsNr);
                        LOGIC.LogicInvoice.SetNullBookingIDForInvoice(guestNr);
                        LOGIC.LogicBooking.DropBookingLodging(bokningsNr);
                                                
                        string choosenPrice;
                        string[] choosenPriceSplit;
                        for (int i = 0; i < listBox_LogReserved.Items.Count; i++)
                        {
                            choosenPrice = listBox_LogReserved.Items[i].ToString();
                            choosenPriceSplit = choosenPrice.Split('\t', '\t', '\t', '\t', '\t');

                            int pris = int.Parse(choosenPriceSplit[2]);
                            string lodgingid = choosenPriceSplit[0].ToString();
                            DateTime startDate = Convert.ToDateTime(choosenPriceSplit[4]);
                            DateTime endDate = Convert.ToDateTime(choosenPriceSplit[5]);


                            BookingPrice(pris.ToString());

                            LOGIC.LogicBooking.ShoppingCart(lodgingid, startDate, endDate);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ett fel uppstod:" + ex);
                }
                textBox_LogSearch.Clear();
                
                button_LogSave.Enabled = true;
                listBox_LogBookingList.DataSource = null;

            }
        }

        /// <summary>
        /// Läser in en privatgästs uppgifter i textboxarna vid dubbelklickning
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewPGuest_DoubleClick(object sender, EventArgs e)
        {

            textBox_LogPrGuestNr.Text = dataGridViewPGuest.CurrentRow.Cells[7].Value.ToString();
            textBox_LogPrFName.Text = dataGridViewPGuest.CurrentRow.Cells[0].Value.ToString();
            textBox_LogPrLName.Text = dataGridViewPGuest.CurrentRow.Cells[1].Value.ToString();
            textBox_LogPrAddress.Text = dataGridViewPGuest.CurrentRow.Cells[2].Value.ToString();
            textBox_LogPrCity.Text = dataGridViewPGuest.CurrentRow.Cells[4].Value.ToString();
            textBox_LogPrZip.Text = dataGridViewPGuest.CurrentRow.Cells[3].Value.ToString();
            textBox_LogPrPhone.Text = dataGridViewPGuest.CurrentRow.Cells[5].Value.ToString();
            textBox_LogPrCredit.Text = dataGridViewPGuest.CurrentRow.Cells[6].Value.ToString();
            textBox_LogDiscount.Text = dataGridViewPGuest.CurrentRow.Cells[8].Value.ToString();
            textBox_LogPrGuestNr.Enabled = false;
            textBox_LogPrFName.Enabled = false;
            textBox_LogPrLName.Enabled = false;
            buttonSparaGäst_Log.Enabled = false;

            if (textBox_LogPrGuestNr.Text != string.Empty) 
            {
                int tempnr = int.Parse(textBox_LogPrGuestNr.Text);
                bindingSource1.DataSource = currentBooking.GetGuestHistory(tempnr);
                               
            }

            if (textBox_LogTotalSum.Text != null)
            {
                decimal totPrice = decimal.Parse(textBox_LogTotalSum.Text);
                decimal credit = decimal.Parse(textBox_LogPrCredit.Text);

                if (credit < totPrice)
                {                    
                    DialogResult rusultat = MessageBox.Show("Gästen överskrider kreditgränsen! \nGästens kredit är för låg för den aktuella bokningen", "Viktigt", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        /// <summary>
        /// Läser in en företagsgästs uppgifter i textboxarna vid dubbelklickning
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewCoGuest_DoubleClick(object sender, EventArgs e)
        {           

            textBox_LogCoOrgNr.Text = dataGridViewCoGuest.CurrentRow.Cells[0].Value.ToString();
            textBox_LogCoName.Text = dataGridViewCoGuest.CurrentRow.Cells[1].Value.ToString();
            textBox_LogCoReference.Text = dataGridViewCoGuest.CurrentRow.Cells[2].Value.ToString();
            textBox_LogCoAddress.Text = dataGridViewCoGuest.CurrentRow.Cells[3].Value.ToString();
            textBox_LogCoZip.Text = dataGridViewCoGuest.CurrentRow.Cells[4].Value.ToString();
            textBox_LogCoCity.Text = dataGridViewCoGuest.CurrentRow.Cells[5].Value.ToString();
            textBox_LogCoPhone.Text = dataGridViewCoGuest.CurrentRow.Cells[6].Value.ToString();
            textBox_LogCoCredit.Text = dataGridViewCoGuest.CurrentRow.Cells[7].Value.ToString();
            textBox_LogCoGuestNr.Text = dataGridViewCoGuest.CurrentRow.Cells[8].Value.ToString();
            textBox_LogDiscount.Text = dataGridViewCoGuest.CurrentRow.Cells[9].Value.ToString();
            textBox_LogCoGuestNr.Enabled = false;
            textBox_LogCoOrgNr.Enabled = false;
            textBox_LogCoName.Enabled = false;
            buttonSparaGästCo.Enabled = false;

            if (textBox_LogTotalSum.Text != null)
            {
                decimal totPrice = decimal.Parse(textBox_LogTotalSum.Text);
                decimal credit = decimal.Parse(textBox_LogCoCredit.Text);

                if (credit < totPrice)
                {
                    DialogResult rusultat = MessageBox.Show("Gästen överskrider kreditgränsen! \nGästens kredit är för låg för den aktuella bokningen", "Viktigt", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            

        }

        private void button2_Click(object sender, EventArgs e)
        {
            listBox1.DataSource = null;
            bindingSourceFreeLodging.DataSource = null;

            try
            {
                int weekNr = int.Parse(comboBoxCampWeekNr.Text);
                DateTime endDate = Convert.ToDateTime(dateTimePicker_CampDateTo.Text);
                DateTime startdate = Convert.ToDateTime(dateTimePicker_CampDateFrom.Text);

                listBox1.DataSource = currentLodging.GetCampFreeLodgin(startdate, endDate, weekNr);
                bindingSourceFreeLodging.DataSource = currentLodging.GetApartmentFreeLodging(startdate, endDate, comboBoxLodgWeekNr.Text);


                if (listBox1.DataSource == null)
                {
                    MessageBox.Show("Inga lediga logier kunde hittas för de angivna datumen.");
                }
                else
                    button_LogSave.Enabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show("Något gick dessvärre fel, error:" + ex);
            }

        }
        


        private void radioButtonVecka_CheckedChanged(object sender, EventArgs e)
        {            
           SearchCamp();
           comboBoxCampWeekNr.Enabled = radioButtonCampWeek.Checked;

        }


        private void radioButtonDygn_CheckedChanged_1(object sender, EventArgs e)
        {
            dateTimePicker_CampDateFrom.Enabled = radioButtonCampDay.Checked;
            dateTimePicker_CampDateTo.Enabled = radioButtonCampDay.Checked;
        }


        //============================================CONFERENCE==================================================================

        //Conftid till dateTime
        private void comboBox_ConTimeFrom_SelectedIndexChanged(object sender, EventArgs e)
        {
            //string confFromString = comboBox_ConTimeFrom.SelectedItem.ToString();
            //DateTime confFrom = Convert.ToDateTime(confFromString);

            //MessageBox.Show(confFrom.ToShortTimeString());
        }

        //Conftid till datetime
        private void comboBox_ConTimeTo_SelectedIndexChanged(object sender, EventArgs e)
        {
            //string confToString = comboBox_ConTimeTo.SelectedItem.ToString();
            //DateTime confTo = Convert.ToDateTime(confToString);

            //MessageBox.Show(confTo.ToShortTimeString());
        }


        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime endDate = Convert.ToDateTime(dateTimePicker_CampDateTo.Text);
                DateTime startDate = Convert.ToDateTime(dateTimePicker_CampDateFrom.Text);

                string s = "\t" + listBox1.SelectedItem.ToString();
                string[] text1 = s.Split('\t');
                string lodgingType = text1[1];
                string price = text1[2];


                string lodgingid = currentLodging.GetLodgingID(startDate, endDate, lodgingType)[0];

                
                if (textBox_LogPrCredit.Text == string.Empty || textBox_LogPrCredit.Text == "") //*
                {
                    if (listBox_LogReserved.DataSource != null)
                    {
                       listBox_LogReserved.DataSource = null;
                       listBox_LogReserved.Items.Add(lodgingid + s);

                        LOGIC.LogicBooking.ShoppingCart(lodgingid, startDate, endDate);
                        BookingPrice(price);
                    }
                   else
                    {
                        listBox_LogReserved.Items.Add(lodgingid + s);

                        LOGIC.LogicBooking.ShoppingCart(lodgingid, startDate, endDate);
                        BookingPrice(price);
                    }
                }
                else
                {
                    decimal totPrice = decimal.Parse(textBox_LogTotalSum.Text);

                    decimal credit = decimal.Parse(textBox_LogPrCredit.Text);

                    decimal tempPrice = decimal.Parse(price);

                    decimal currentPrice = tempPrice + totPrice;

                    if (currentPrice > credit)
                    {
                        DialogResult resultat = MessageBox.Show("Gästen överskrider kreditgränsen! \nGästens kredit är för låg för den aktuella bokningen", "Viktigt", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else if (listBox_LogReserved.DataSource == null)
                    {
                        listBox_LogReserved.DataSource = null;
                        listBox_LogReserved.Items.Add(lodgingid + s);

                        LOGIC.LogicBooking.ShoppingCart(lodgingid, startDate, endDate);
                        BookingPrice(price);
                    }
                    else
                    {
                        listBox_LogReserved.Items.Add(lodgingid + s);

                        LOGIC.LogicBooking.ShoppingCart(lodgingid, startDate, endDate);
                        BookingPrice(price);
                    }

                }

            }
               
            catch
            {
                MessageBox.Show("Det finns inga logier kvar av den typen.");
            }
        }

        //Sök ledig konferens
        private void button_ConSearch_Click(object sender, EventArgs e)
        {
            //Gör om vald tidpunkt från comboboxarna till DateTimeformat.
            string confTimeFromString = comboBox_ConTimeFrom.SelectedItem.ToString();
            DateTime confTimeFrom = Convert.ToDateTime(confTimeFromString);
            string confTimeToString = comboBox_ConTimeTo.SelectedItem.ToString();
            DateTime confTimeTo = Convert.ToDateTime(confTimeToString);

            DateTime confDateFrom = dateTimePicker_ConfDateFrom.Value;
            DateTime confDateTo = dateTimePicker_ConfDateTo.Value;

            try
            {
                if (confTimeFrom == confTimeTo)
                {
                    MessageBox.Show("Felaktigt bokningsintervall, du måste boka konferensrummet minst en timme.");
                }

                else
                {
                    //bindingSourceFreeConference.DataSource = currentConference.GetFreeConference(confTimeFrom, confTimeTo, confDateFrom, confDateTo);
                    //bindingSourceConfPrice.DataSource = currentConferce.GetApartmentFreeLodging(startdate, endDate, comboBoxWeckoNr_Log.Text);





                    //        if (bindingSourceLogi.DataSource == null)
                    //            MessageBox.Show("Inga lediga logier kunde hittas för de angivna datumen.");

                    //        else
                    //            button_LogSave.Enabled = true;
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Något gick dessvärre fel, error:" + ex);
            }
        }

        private void radioButtonConfWeek_CheckedChanged(object sender, EventArgs e)
        {
            SearchConference();
            comboBoxConfWeek.Enabled = radioButtonCampWeek.Checked;
        }

        private void radioButtonConfDay_CheckedChanged(object sender, EventArgs e)
        {
            comboBoxConfWeek.Enabled = false;
            dateTimePicker_ConfDateFrom.Enabled = radioButtonConfDay.Checked;
            dateTimePicker_ConfDateTo.Enabled = radioButtonConfDay.Checked;
        }

        private void radioButtonConfHour_CheckedChanged(object sender, EventArgs e)
        {  
            dateTimePicker_ConfDateFrom.Enabled = radioButtonConfHour.Checked;
            comboBoxConfWeek.Enabled = false;
            comboBox_ConTimeFrom.Visible = radioButtonConfHour.Checked;
            comboBox_ConTimeTo.Visible = radioButtonConfHour.Checked;
            label35.Visible = radioButtonConfHour.Checked;
            label40.Visible = radioButtonConfHour.Checked;

            dateTimePicker_ConfDateTo.Value = dateTimePicker_ConfDateFrom.Value;        
        }

        private void listBoxShowFreeLodgingAndCamp_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void comboBoxConfWeek_SelectedIndexChanged(object sender, EventArgs e)
        {
            SearchConference();
        }

        private void buttonConfShowLodging_Click(object sender, EventArgs e)
        {
            SearchFreeConference();               
        }

        /// <summary>
        /// Metod som söker ut lediga konferensrum
        /// </summary>
        private void SearchFreeConference()
        {
            DateTime startDate;
            DateTime endDate;
            listBox3.DataSource = null;
            bindingSourceFreeConference.DataSource = null;


            if (comboBox_ConTimeTo.Text == "" && comboBox_ConTimeFrom.Text == "")
            {
                startDate = Convert.ToDateTime(dateTimePicker_ConfDateFrom.Text);//+ " " + DateTime.Now.ToShortTimeString());
                endDate = Convert.ToDateTime(dateTimePicker_ConfDateTo.Text);//+ " " + DateTime.Now.ToShortTimeString());
            }
            else
            {
                startDate = Convert.ToDateTime(dateTimePicker_ConfDateFrom.Text + " " + comboBox_ConTimeFrom.Text);
                endDate = Convert.ToDateTime(dateTimePicker_ConfDateTo.Text + " " + comboBox_ConTimeTo.Text);
            }

            int weekNr = int.Parse(comboBoxConfWeek.Text);

            //bindingSourceLogi.DataSource = currentLodging.GetCampFreeLodging(startdate, endDate, comboBoxWeckoNr_Log.Text, lodgingType);
            listBox3.DataSource = currentConference.GetConferencePrice(startDate, endDate, weekNr);
            bindingSourceFreeConference.DataSource = currentConference.GetFreeConference(startDate, endDate, weekNr);

            if (bindingSourceFreeConference == null)
            {
                MessageBox.Show("Inga lediga logier kunde hittas för de angivna datumen.");
            }
            else
            {
                button_LogSave.Enabled = true;
            }
         }

        private void dateTimePicker_ConfDateFrom_ValueChanged(object sender, EventArgs e)
        {
            if (radioButtonConfHour.Checked == true)
            { dateTimePicker_ConfDateTo.Value = dateTimePicker_ConfDateFrom.Value; }
            else
            { }
        }

        private void button_ConfAdd_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime startDate;
                DateTime endDate;
                if (dateTimePicker_ConfDateFrom.Text == "" && dateTimePicker_CampDateTo.Text == "")
                {

                    startDate = Convert.ToDateTime(dateTimePicker_ConfDateFrom.Text);
                    endDate = Convert.ToDateTime(dateTimePicker_ConfDateTo.Text);

                }
                else
                {
                    startDate = Convert.ToDateTime(dateTimePicker_ConfDateFrom.Text + " " + comboBox_ConTimeFrom.Text);
                    endDate = Convert.ToDateTime(dateTimePicker_ConfDateTo.Text + " " + comboBox_ConTimeTo.Text);
                }

                string s = "\t" + listBox3.SelectedItem.ToString();
                string[] text1 = s.Split('\t');
                string lodgingType = text1[1] + "en";
                string price = text1[2];

                string lodgingid = currentConference.GetConferenceID(startDate, endDate, lodgingType)[0];


                listBox_LogReserved.Items.Add(lodgingid + s);

                LOGIC.LogicBooking.ShoppingCart(lodgingid, startDate, endDate);
                BookingPrice(price);
               
            }
            catch (Exception)
            {

                DialogResult result = MessageBox.Show("Det finns inga konferenser kvar av den typen.", "Viktigt", MessageBoxButtons.OK, MessageBoxIcon.Hand); 
            }          
        }

        private void Lodging_Load(object sender, EventArgs e)
        {           
            comboBoxPeriod_Log.Text = "Helvecka";           
        }

        private void UpdateWeekNr()
        {
            comboBoxCampWeekNr.Text = currentLodging.WeekNrFromDate(dateTimePicker_CampDateFrom.Value).ToString();
        }

      
        private void comboBoxCampWeekNr_SelectedIndexChanged(object sender, EventArgs e)
        {
            SearchCamp();
        }

        private void dateTimePicker_CampDateFrom_ValueChanged(object sender, EventArgs e)
        {
            UpdateWeekNr();
        }
                     
    }
}      




     

       



      
      

        

       
      

       

        










        
    

